Importing my libraries¶

In [1]:
# AWS SDK for Python
import boto3
from botocore.exceptions import ClientError

# Image processing
from PIL import Image, ImageDraw, ImageFont, ImageFilter, ImageOps, ImageEnhance

# Data analysis and visualization
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# Standard Python libraries for web requests and file handling
import requests
import zipfile
import os
import re
import io

# Display utilities
from IPython.display import display
In [2]:
import boto3
import json
import boto3
import pandas as pd 
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
from IPython.display import display
In [3]:
# import libraries
import requests
import zipfile
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# image stuff
# import face_recognition
from PIL import Image, ImageDraw, ImageFont, ImageFilter, ImageOps, ImageEnhance
# from google.colab.patches import cv2_imshow

Trying Out Detect Faces¶

In [4]:
def detect_faces(photo, bucket, region):
    
    session = boto3.Session()
    
    client = session.client('rekognition', region_name=region)

    response = client.detect_faces(Image={'S3Object':{'Bucket':bucket,'Name':photo}},
                                   Attributes=['ALL'])

    print('Detected faces for ' + photo)
    for faceDetail in response['FaceDetails']:
        print(f"The detected face is between {faceDetail['AgeRange']['Low']} and {faceDetail['AgeRange']['High']}  years old")

        print('Here are the other attributes:')
        print(json.dumps(faceDetail, indent=4, sort_keys=True))

        # Access predictions for individual face details and print them
        print(f"Gender    : {faceDetail['Gender']}" )
        print(f"Smile     : {faceDetail['Smile']}" )
        print(f"Eyeglasses: {faceDetail['Eyeglasses']}" )
        print(f"Emotions  : {faceDetail['Emotions'][0]}" )

    return len(response['FaceDetails'])
    

photo='Eric_Mayo.jpg'
bucket='mayoe23-final-bucket'
region='us-east-1'
face_count=detect_faces(photo, bucket, region)
print("Faces detected: " + str(face_count))
Detected faces for Eric_Mayo.jpg
The detected face is between 26 and 34  years old
Here are the other attributes:
{
    "AgeRange": {
        "High": 34,
        "Low": 26
    },
    "Beard": {
        "Confidence": 99.98954010009766,
        "Value": true
    },
    "BoundingBox": {
        "Height": 0.26029014587402344,
        "Left": 0.42233142256736755,
        "Top": 0.24128423631191254,
        "Width": 0.14568157494068146
    },
    "Confidence": 99.99990844726562,
    "Emotions": [
        {
            "Confidence": 100.0,
            "Type": "HAPPY"
        },
        {
            "Confidence": 0.005650520324707031,
            "Type": "CALM"
        },
        {
            "Confidence": 0.004684925079345703,
            "Type": "CONFUSED"
        },
        {
            "Confidence": 0.0003427267074584961,
            "Type": "SURPRISED"
        },
        {
            "Confidence": 0.0,
            "Type": "ANGRY"
        },
        {
            "Confidence": 0.0,
            "Type": "DISGUSTED"
        },
        {
            "Confidence": 0.0,
            "Type": "FEAR"
        },
        {
            "Confidence": 0.0,
            "Type": "SAD"
        }
    ],
    "EyeDirection": {
        "Confidence": 99.99160766601562,
        "Pitch": -14.985841751098633,
        "Yaw": 2.6591317653656006
    },
    "Eyeglasses": {
        "Confidence": 100.0,
        "Value": true
    },
    "EyesOpen": {
        "Confidence": 98.65709686279297,
        "Value": true
    },
    "FaceOccluded": {
        "Confidence": 99.9394760131836,
        "Value": false
    },
    "Gender": {
        "Confidence": 99.94911193847656,
        "Value": "Male"
    },
    "Landmarks": [
        {
            "Type": "eyeLeft",
            "X": 0.45851635932922363,
            "Y": 0.336690217256546
        },
        {
            "Type": "eyeRight",
            "X": 0.5254401564598083,
            "Y": 0.34097394347190857
        },
        {
            "Type": "mouthLeft",
            "X": 0.4598765969276428,
            "Y": 0.42811715602874756
        },
        {
            "Type": "mouthRight",
            "X": 0.5156224966049194,
            "Y": 0.4317719638347626
        },
        {
            "Type": "nose",
            "X": 0.48538362979888916,
            "Y": 0.37873783707618713
        },
        {
            "Type": "leftEyeBrowLeft",
            "X": 0.43599018454551697,
            "Y": 0.3166728615760803
        },
        {
            "Type": "leftEyeBrowRight",
            "X": 0.47206202149391174,
            "Y": 0.3071371912956238
        },
        {
            "Type": "leftEyeBrowUp",
            "X": 0.45369961857795715,
            "Y": 0.30266472697257996
        },
        {
            "Type": "rightEyeBrowLeft",
            "X": 0.5103328227996826,
            "Y": 0.30948349833488464
        },
        {
            "Type": "rightEyeBrowRight",
            "X": 0.5520758032798767,
            "Y": 0.3239831328392029
        },
        {
            "Type": "rightEyeBrowUp",
            "X": 0.5307261943817139,
            "Y": 0.3074575960636139
        },
        {
            "Type": "leftEyeLeft",
            "X": 0.4471665918827057,
            "Y": 0.3365420699119568
        },
        {
            "Type": "leftEyeRight",
            "X": 0.4716590344905853,
            "Y": 0.33833083510398865
        },
        {
            "Type": "leftEyeUp",
            "X": 0.4582666754722595,
            "Y": 0.3315728008747101
        },
        {
            "Type": "leftEyeDown",
            "X": 0.458595871925354,
            "Y": 0.34062814712524414
        },
        {
            "Type": "rightEyeLeft",
            "X": 0.5120620131492615,
            "Y": 0.34089457988739014
        },
        {
            "Type": "rightEyeRight",
            "X": 0.5377001166343689,
            "Y": 0.3423546254634857
        },
        {
            "Type": "rightEyeUp",
            "X": 0.5254073739051819,
            "Y": 0.33584538102149963
        },
        {
            "Type": "rightEyeDown",
            "X": 0.5247785449028015,
            "Y": 0.3448822796344757
        },
        {
            "Type": "noseLeft",
            "X": 0.47496873140335083,
            "Y": 0.39331209659576416
        },
        {
            "Type": "noseRight",
            "X": 0.49959784746170044,
            "Y": 0.39492353796958923
        },
        {
            "Type": "mouthUp",
            "X": 0.48596471548080444,
            "Y": 0.4150463938713074
        },
        {
            "Type": "mouthDown",
            "X": 0.4853469431400299,
            "Y": 0.443823903799057
        },
        {
            "Type": "leftPupil",
            "X": 0.45851635932922363,
            "Y": 0.336690217256546
        },
        {
            "Type": "rightPupil",
            "X": 0.5254401564598083,
            "Y": 0.34097394347190857
        },
        {
            "Type": "upperJawlineLeft",
            "X": 0.4253995418548584,
            "Y": 0.348438560962677
        },
        {
            "Type": "midJawlineLeft",
            "X": 0.43420660495758057,
            "Y": 0.44676294922828674
        },
        {
            "Type": "chinBottom",
            "X": 0.4852495491504669,
            "Y": 0.4951191544532776
        },
        {
            "Type": "midJawlineRight",
            "X": 0.5520117878913879,
            "Y": 0.4544123113155365
        },
        {
            "Type": "upperJawlineRight",
            "X": 0.5709078907966614,
            "Y": 0.3575979769229889
        }
    ],
    "MouthOpen": {
        "Confidence": 99.60477447509766,
        "Value": true
    },
    "Mustache": {
        "Confidence": 99.96615600585938,
        "Value": true
    },
    "Pose": {
        "Pitch": 10.909923553466797,
        "Roll": 1.3273253440856934,
        "Yaw": -5.24214506149292
    },
    "Quality": {
        "Brightness": 79.5440444946289,
        "Sharpness": 97.45164489746094
    },
    "Smile": {
        "Confidence": 99.39434814453125,
        "Value": true
    },
    "Sunglasses": {
        "Confidence": 99.99996948242188,
        "Value": false
    }
}
Gender    : {'Value': 'Male', 'Confidence': 99.94911193847656}
Smile     : {'Value': True, 'Confidence': 99.39434814453125}
Eyeglasses: {'Value': True, 'Confidence': 100.0}
Emotions  : {'Type': 'HAPPY', 'Confidence': 100.0}
Faces detected: 1

Trying Out CompareFaces¶

In [5]:
def compare_faces(bucket, sourceFile, targetFile):
    client = boto3.client('rekognition')

    response = client.compare_faces(SimilarityThreshold=80,
                                    SourceImage={'S3Object': {'Bucket': bucket, 'Name': sourceFile}},
                                    TargetImage={'S3Object': {'Bucket': bucket, 'Name': targetFile}})

    for faceMatch in response['FaceMatches']:
        position = faceMatch['Face']['BoundingBox']
        print(f'face similarity {faceMatch["Similarity"]:.2f}%')
       

    return faceMatch["Similarity"]

# Specify the S3 bucket name
bucket_name = 'mayoe23-final-bucket'

# S3 object keys (file names in the bucket)
source_file = 'Eric_Mayo.jpg'
target_file = 'Eric_Mayo_aged.jpg'

match_similarity = compare_faces(bucket_name, source_file, target_file)
face similarity 93.13%

Side-by-side Comparison¶

In [6]:
def display_images_side_by_side(bucket, image_key1, image_key2, similarity):
    s3 = boto3.client('s3')

    # Get the images from S3
    def get_image_from_s3(bucket, key):
        response = s3.get_object(Bucket=bucket, Key=key)
        image_data = response['Body'].read()
        return Image.open(BytesIO(image_data))

    image1 = get_image_from_s3(bucket, image_key1)
    image2 = get_image_from_s3(bucket, image_key2)

    # Rest of your code to process and display images
    width1, height1 = image1.size
    width2, height2 = image2.size

    new_image = Image.new("RGB", (width1 + width2, max(height1, height2)))
    new_image.paste(image1, (0, 0))
    new_image.paste(image2, (width1, 0))

    # Add text
    text = f'{similarity:.2f} % MATCH'
    font = ImageFont.truetype(r"C:\Users\ericm\OneDrive\Desktop\Data Management\Roboto-Medium.ttf", size=48)  # Update path to font
    draw = ImageDraw.Draw(new_image)
    text_width, text_height = draw.textsize(text, font)
    left, top = 900, 100
    draw.rectangle(((left, top), (left + text_width, top + text_height)), fill=(255, 255, 255, 128))
    draw.text((left, top), text, font=font, fill=(0, 0, 0, 255))

     # Display the image
    display(new_image)

# Example usage
# Specify the S3 bucket name
bucket_name = 'mayoe23-final-bucket'

# S3 object keys (file names in the bucket)
image_key1 = 'Eric_Mayo.jpg'
image_key2 = 'Eric_Mayo_aged.jpg'
# similarity = 0.8  # Example similarity score

display_images_side_by_side(bucket_name, image_key1, image_key2, match_similarity)
C:\Users\ericm\AppData\Local\Temp\ipykernel_37592\495844869.py:25: DeprecationWarning: textsize is deprecated and will be removed in Pillow 10 (2023-07-01). Use textbbox or textlength instead.
  text_width, text_height = draw.textsize(text, font)

Making my Collection¶

In [7]:
# Add faces to a collection
import boto3

def create_rekognition_collection(collection_id):
    client = boto3.client('rekognition')
    
    # Check if the collection already exists
    existing_collections = client.list_collections()
    if collection_id in existing_collections['CollectionIds']:
        print(f"Collection {collection_id} already exists.")
        return

    # Create the collection if it doesn't exist
    try:
        client.create_collection(CollectionId=collection_id)
        print(f"Collection {collection_id} created.")
    except client.exceptions.ResourceAlreadyExistsException:
        print(f"Collection {collection_id} already exists.")
        
    

def add_faces_to_collection(bucket, collection_id):
    s3_client = boto3.client('s3')
    rekognition_client = boto3.client('rekognition')

    # List objects in the bucket
    response = s3_client.list_objects_v2(Bucket=bucket)

    if 'Contents' in response:
        for obj in response['Contents']:
            image = obj['Key']
            
            # Index the face(s) in the image
            rekognition_client.index_faces(CollectionId=collection_id,
                                           Image={'S3Object': {'Bucket': bucket, 'Name': image}},
                                           ExternalImageId=image, # this is the name of the person!!! 
                                           MaxFaces=1,
                                           QualityFilter="AUTO",
                                           DetectionAttributes=['ALL'])

            print(f"Added {image} to collection {collection_id}")

# Example usage

collection_id = "mayoe23-face-collection"
bucket_name = 'mayoe23-final-bucket'

create_rekognition_collection(collection_id)
add_faces_to_collection(bucket_name, collection_id)
Collection mayoe23-face-collection already exists.
Added Alfredo_Enrique_Suarez.jpg to collection mayoe23-face-collection
Added Alfredo_Enrique_Suarez_aged.jpg to collection mayoe23-face-collection
Added Alicia_Rand_Bodoia.jpg to collection mayoe23-face-collection
Added Alicia_Rand_Bodoia_aged.jpg to collection mayoe23-face-collection
Added Allen_Gail_Smith.jpg to collection mayoe23-face-collection
Added Allen_Gail_Smith_aged.jpg to collection mayoe23-face-collection
Added Amanda_Renner_Gild.jpg to collection mayoe23-face-collection
Added Amanda_Renner_Gild_aged.jpg to collection mayoe23-face-collection
Added Andrea_Chen.jpg to collection mayoe23-face-collection
Added Andrea_Chen_aged.jpg to collection mayoe23-face-collection
Added Andrew_Dubois.jpg to collection mayoe23-face-collection
Added Andrew_Dubois_aged.jpg to collection mayoe23-face-collection
Added Andrew_Lloyd_Loftis.jpg to collection mayoe23-face-collection
Added Andrew_Lloyd_Loftis_aged.jpg to collection mayoe23-face-collection
Added Angela_Waszkiewicz.jpg to collection mayoe23-face-collection
Added Angela_Waszkiewicz_aged.jpg to collection mayoe23-face-collection
Added Anne_M_Perry.jpg to collection mayoe23-face-collection
Added Anne_M_Perry_aged.jpg to collection mayoe23-face-collection
Added Anoush_U_Shah.jpg to collection mayoe23-face-collection
Added Anoush_U_Shah_aged.jpg to collection mayoe23-face-collection
Added Anthony_X_Ayala.jpg to collection mayoe23-face-collection
Added Anthony_X_Ayala_aged.jpg to collection mayoe23-face-collection
Added Benjamin_Pyung-Hwa_Aikens.jpg to collection mayoe23-face-collection
Added Benjamin_Pyung-Hwa_Aikens_aged.jpg to collection mayoe23-face-collection
Added Bingnan_Lei.jpg to collection mayoe23-face-collection
Added Bingnan_Lei_aged.jpg to collection mayoe23-face-collection
Added Bingyu_Li.jpg to collection mayoe23-face-collection
Added Bingyu_Li_aged.jpg to collection mayoe23-face-collection
Added Bintong_Zhai.jpg to collection mayoe23-face-collection
Added Bintong_Zhai_aged.jpg to collection mayoe23-face-collection
Added Boyan_Wei.jpg to collection mayoe23-face-collection
Added Boyan_Wei_aged.jpg to collection mayoe23-face-collection
Added Boyu_Zheng.jpg to collection mayoe23-face-collection
Added Boyu_Zheng_aged.jpg to collection mayoe23-face-collection
Added Bryce_Charles_Drynan.jpg to collection mayoe23-face-collection
Added Bryce_Charles_Drynan_aged.jpg to collection mayoe23-face-collection
Added Chengzhan_Shen.jpg to collection mayoe23-face-collection
Added Chengzhan_Shen_aged.jpg to collection mayoe23-face-collection
Added Cheuk_Yui_Marcus_Chan.jpg to collection mayoe23-face-collection
Added Cheuk_Yui_Marcus_Chan_aged.jpg to collection mayoe23-face-collection
Added Chioke_K_Bellamy.jpg to collection mayoe23-face-collection
Added Chioke_K_Bellamy_aged.jpg to collection mayoe23-face-collection
Added Christopher_Craig_Kenney.jpg to collection mayoe23-face-collection
Added Christopher_Craig_Kenney_aged.jpg to collection mayoe23-face-collection
Added Christopher_David_Koontz.jpg to collection mayoe23-face-collection
Added Christopher_David_Koontz_aged.jpg to collection mayoe23-face-collection
Added Cole_Ritchey.jpg to collection mayoe23-face-collection
Added Cole_Ritchey_aged.jpg to collection mayoe23-face-collection
Added Daniel_Madden_Sheedy.jpg to collection mayoe23-face-collection
Added Daniel_Madden_Sheedy_aged.jpg to collection mayoe23-face-collection
Added Dillon_Hunter_Aryeh.jpg to collection mayoe23-face-collection
Added Dillon_Hunter_Aryeh_aged.jpg to collection mayoe23-face-collection
Added Dongqiao_Tang.jpg to collection mayoe23-face-collection
Added Dongqiao_Tang_aged.jpg to collection mayoe23-face-collection
Added Edward_Cheongjoun_Hyun.jpg to collection mayoe23-face-collection
Added Edward_Cheongjoun_Hyun_aged.jpg to collection mayoe23-face-collection
Added Elizabeth_G_Higgins.jpg to collection mayoe23-face-collection
Added Elizabeth_G_Higgins_aged.jpg to collection mayoe23-face-collection
Added Emmanuel_Thomas_George_Skora.jpg to collection mayoe23-face-collection
Added Emmanuel_Thomas_George_Skora_aged.jpg to collection mayoe23-face-collection
Added Eric_Mayo.jpg to collection mayoe23-face-collection
Added Eric_Mayo_aged.jpg to collection mayoe23-face-collection
Added Estefani_Santiago_Gatica.jpg to collection mayoe23-face-collection
Added Estefani_Santiago_Gatica_aged.jpg to collection mayoe23-face-collection
Added Evan_Anderson_Gilbert.jpg to collection mayoe23-face-collection
Added Evan_Anderson_Gilbert_aged.jpg to collection mayoe23-face-collection
Added Garhett_William_Sessions.jpg to collection mayoe23-face-collection
Added Garhett_William_Sessions_aged.jpg to collection mayoe23-face-collection
Added George_Basil_Economus.jpg to collection mayoe23-face-collection
Added George_Basil_Economus_aged.jpg to collection mayoe23-face-collection
Added Guangxin_Bao.jpg to collection mayoe23-face-collection
Added Guangxin_Bao_aged.jpg to collection mayoe23-face-collection
Added Hangfei_Lyu.jpg to collection mayoe23-face-collection
Added Hangfei_Lyu_aged.jpg to collection mayoe23-face-collection
Added Hanshuai_Shi.jpg to collection mayoe23-face-collection
Added Hanshuai_Shi_aged.jpg to collection mayoe23-face-collection
Added Haopeng_Liu.jpg to collection mayoe23-face-collection
Added Haopeng_Liu_aged.jpg to collection mayoe23-face-collection
Added Harve_E_Criqui.jpg to collection mayoe23-face-collection
Added Harve_E_Criqui_aged.jpg to collection mayoe23-face-collection
Added Helen_Kidane_Haile.jpg to collection mayoe23-face-collection
Added Helen_Kidane_Haile_aged.jpg to collection mayoe23-face-collection
Added Hewei_Shen.jpg to collection mayoe23-face-collection
Added Hewei_Shen_aged.jpg to collection mayoe23-face-collection
Added IMG_1883.jpg to collection mayoe23-face-collection
Added IMG_1884.jpg to collection mayoe23-face-collection
Added IMG_1886.jpg to collection mayoe23-face-collection
Added Jackson_R_Harper.jpg to collection mayoe23-face-collection
Added Jackson_R_Harper_aged.jpg to collection mayoe23-face-collection
Added Jacob_Philip_Rockaway.jpg to collection mayoe23-face-collection
Added Jacob_Philip_Rockaway_aged.jpg to collection mayoe23-face-collection
Added Jash_Sanjaybhai_Vachhani.jpg to collection mayoe23-face-collection
Added Jash_Sanjaybhai_Vachhani_aged.jpg to collection mayoe23-face-collection
Added Jax_Francis_Revfi.jpg to collection mayoe23-face-collection
Added Jax_Francis_Revfi_aged.jpg to collection mayoe23-face-collection
Added Jennifer_Ontiveros-Olivas.jpg to collection mayoe23-face-collection
Added Jennifer_Ontiveros-Olivas_aged.jpg to collection mayoe23-face-collection
Added Jeremy_Brian_Nurding.jpg to collection mayoe23-face-collection
Added Jeremy_Brian_Nurding_aged.jpg to collection mayoe23-face-collection
Added Jiacheng_Wang.jpg to collection mayoe23-face-collection
Added Jiacheng_Wang_aged.jpg to collection mayoe23-face-collection
Added Jiahao_Ma.jpg to collection mayoe23-face-collection
Added Jiahao_Ma_aged.jpg to collection mayoe23-face-collection
Added Jiahua_Wu.jpg to collection mayoe23-face-collection
Added Jiahua_Wu_aged.jpg to collection mayoe23-face-collection
Added Jiaming_Zhang.jpg to collection mayoe23-face-collection
Added Jiaming_Zhang_aged.jpg to collection mayoe23-face-collection
Added Jodie_Elizabeth_Brine.jpg to collection mayoe23-face-collection
Added Jodie_Elizabeth_Brine_aged.jpg to collection mayoe23-face-collection
Added John_William_Null.jpg to collection mayoe23-face-collection
Added John_William_Null_aged.jpg to collection mayoe23-face-collection
Added Joseph_Macon_Barker.jpg to collection mayoe23-face-collection
Added Joseph_Macon_Barker_aged.jpg to collection mayoe23-face-collection
Added Joseph_Miller_Hirsch.jpg to collection mayoe23-face-collection
Added Joseph_Miller_Hirsch_aged.jpg to collection mayoe23-face-collection
Added Kaamil_Farooqi.jpg to collection mayoe23-face-collection
Added Kaamil_Farooqi_aged.jpg to collection mayoe23-face-collection
Added Kaitlyn_R_Vickers.jpg to collection mayoe23-face-collection
Added Kaitlyn_R_Vickers_aged.jpg to collection mayoe23-face-collection
Added Kaushik_Rajaram.jpg to collection mayoe23-face-collection
Added Kaushik_Rajaram_aged.jpg to collection mayoe23-face-collection
Added Kayla_Marie_Williams.jpg to collection mayoe23-face-collection
Added Kayla_Marie_Williams_aged.jpg to collection mayoe23-face-collection
Added Kendall_Ashley_Hilson.jpg to collection mayoe23-face-collection
Added Kendall_Ashley_Hilson_aged.jpg to collection mayoe23-face-collection
Added Khushi_Arya.jpg to collection mayoe23-face-collection
Added Khushi_Arya_aged.jpg to collection mayoe23-face-collection
Added Kyle_John_Wiblishauser.jpg to collection mayoe23-face-collection
Added Kyle_John_Wiblishauser_aged.jpg to collection mayoe23-face-collection
Added Latham_Alexander_Weaver.jpg to collection mayoe23-face-collection
Added Latham_Alexander_Weaver_aged.jpg to collection mayoe23-face-collection
Added Lauren_Elizabeth_Johnson.jpg to collection mayoe23-face-collection
Added Lauren_Elizabeth_Johnson_aged.jpg to collection mayoe23-face-collection
Added Logan_Trujillo.jpg to collection mayoe23-face-collection
Added Logan_Trujillo_aged.jpg to collection mayoe23-face-collection
Added Lu_Xing.jpg to collection mayoe23-face-collection
Added Lu_Xing_aged.jpg to collection mayoe23-face-collection
Added Luying_Huang.jpg to collection mayoe23-face-collection
Added Luying_Huang_aged.jpg to collection mayoe23-face-collection
Added Manling_Shi.jpg to collection mayoe23-face-collection
Added Manling_Shi_aged.jpg to collection mayoe23-face-collection
Added Marcus_Cole_cooper.jpg to collection mayoe23-face-collection
Added Marcus_Cole_cooper_aged.jpg to collection mayoe23-face-collection
Added Mary_Martha_Milcoff.jpg to collection mayoe23-face-collection
Added Mary_Martha_Milcoff_aged.jpg to collection mayoe23-face-collection
Added Mary_Michele_Troise.jpg to collection mayoe23-face-collection
Added Mary_Michele_Troise_aged.jpg to collection mayoe23-face-collection
Added Max_Koontz.jpg to collection mayoe23-face-collection
Added Max_Koontz_aged.jpg to collection mayoe23-face-collection
Added Meghan_O_Malley.jpg to collection mayoe23-face-collection
Added Meghan_O_Malley_aged.jpg to collection mayoe23-face-collection
Added Mengyao_Liu.jpg to collection mayoe23-face-collection
Added Mengyao_Liu_aged.jpg to collection mayoe23-face-collection
Added Meryl_Criswell_Kaduboski.jpg to collection mayoe23-face-collection
Added Meryl_Criswell_Kaduboski_aged.jpg to collection mayoe23-face-collection
Added Michael_Jason_Vejsiri.jpg to collection mayoe23-face-collection
Added Michael_Jason_Vejsiri_aged.jpg to collection mayoe23-face-collection
Added Michelle_Monica_Saikali.jpg to collection mayoe23-face-collection
Added Michelle_Monica_Saikali_aged.jpg to collection mayoe23-face-collection
Added Millie_C_Garrett.jpg to collection mayoe23-face-collection
Added Millie_C_Garrett_aged.jpg to collection mayoe23-face-collection
Added Natalie_Weiner.jpg to collection mayoe23-face-collection
Added Natalie_Weiner_aged.jpg to collection mayoe23-face-collection
Added Nathalie_Lisa_Friedman.jpg to collection mayoe23-face-collection
Added Nathalie_Lisa_Friedman_aged.jpg to collection mayoe23-face-collection
Added Nathanael_Hunter_Kraus.jpg to collection mayoe23-face-collection
Added Nathanael_Hunter_Kraus_aged.jpg to collection mayoe23-face-collection
Added Nicholas_J_Sundberg.jpg to collection mayoe23-face-collection
Added Nicholas_J_Sundberg_aged.jpg to collection mayoe23-face-collection
Added Nicolson_Charles_Panos.jpg to collection mayoe23-face-collection
Added Nicolson_Charles_Panos_aged.jpg to collection mayoe23-face-collection
Added Niklas_Jozef_Baldis.jpg to collection mayoe23-face-collection
Added Niklas_Jozef_Baldis_aged.jpg to collection mayoe23-face-collection
Added Patrick_Ryan_Weimaker.jpg to collection mayoe23-face-collection
Added Patrick_Ryan_Weimaker_aged.jpg to collection mayoe23-face-collection
Added Qian_Chen.jpg to collection mayoe23-face-collection
Added Qian_Chen_aged.jpg to collection mayoe23-face-collection
Added Qin_Miao.jpg to collection mayoe23-face-collection
Added Qin_Miao_aged.jpg to collection mayoe23-face-collection
Added Quinn_Poole.jpg to collection mayoe23-face-collection
Added Quinn_Poole_aged.jpg to collection mayoe23-face-collection
Added Raleigh_Coolidge_Conway.jpg to collection mayoe23-face-collection
Added Raleigh_Coolidge_Conway_aged.jpg to collection mayoe23-face-collection
Added Reid_Powers_Walker.jpg to collection mayoe23-face-collection
Added Reid_Powers_Walker_aged.jpg to collection mayoe23-face-collection
Added Ruochen_Bao.jpg to collection mayoe23-face-collection
Added Ruochen_Bao_aged.jpg to collection mayoe23-face-collection
Added Ryan_Marek_Smith.jpg to collection mayoe23-face-collection
Added Ryan_Marek_Smith_aged.jpg to collection mayoe23-face-collection
Added Samantha_O_Brien.jpg to collection mayoe23-face-collection
Added Samantha_O_Brien_aged.jpg to collection mayoe23-face-collection
Added Savannah_Kayla_Littlejohn.jpg to collection mayoe23-face-collection
Added Savannah_Kayla_Littlejohn_aged.jpg to collection mayoe23-face-collection
Added Sebastian_Andres_Lopez-Ibanez.jpg to collection mayoe23-face-collection
Added Sebastian_Andres_Lopez-Ibanez_aged.jpg to collection mayoe23-face-collection
Added Shanay_Nimish_Sonawala.jpg to collection mayoe23-face-collection
Added Shanay_Nimish_Sonawala_aged.jpg to collection mayoe23-face-collection
Added Shenger_Zhou.jpg to collection mayoe23-face-collection
Added Shenger_Zhou_aged.jpg to collection mayoe23-face-collection
Added Shenghao_Yang.jpg to collection mayoe23-face-collection
Added Shenghao_Yang_aged.jpg to collection mayoe23-face-collection
Added Shenzhe_Lian.jpg to collection mayoe23-face-collection
Added Shenzhe_Lian_aged.jpg to collection mayoe23-face-collection
Added Shuzhe_Wang.jpg to collection mayoe23-face-collection
Added Shuzhe_Wang_aged.jpg to collection mayoe23-face-collection
Added Siyu_Lin.jpg to collection mayoe23-face-collection
Added Siyu_Lin_aged.jpg to collection mayoe23-face-collection
Added Skylour_Sebastian_Winakur.jpg to collection mayoe23-face-collection
Added Skylour_Sebastian_Winakur_aged.jpg to collection mayoe23-face-collection
Added Songlin_Liu.jpg to collection mayoe23-face-collection
Added Songlin_Liu_aged.jpg to collection mayoe23-face-collection
Added Tianyi_Chen.jpg to collection mayoe23-face-collection
Added Tianyi_Chen_aged.jpg to collection mayoe23-face-collection
Added Tianyi_Yin.jpg to collection mayoe23-face-collection
Added Tianyi_Yin_aged.jpg to collection mayoe23-face-collection
Added Tianyu_Cui.jpg to collection mayoe23-face-collection
Added Tianyu_Cui_aged.jpg to collection mayoe23-face-collection
Added Trinity_Nicole_Elliott.jpg to collection mayoe23-face-collection
Added Trinity_Nicole_Elliott_aged.jpg to collection mayoe23-face-collection
Added Wei_Tan.jpg to collection mayoe23-face-collection
Added Wei_Tan_aged.jpg to collection mayoe23-face-collection
Added Wentong_Guo.jpg to collection mayoe23-face-collection
Added Wentong_Guo_aged.jpg to collection mayoe23-face-collection
Added Whitney_Joyce_Isbell.jpg to collection mayoe23-face-collection
Added Whitney_Joyce_Isbell_aged.jpg to collection mayoe23-face-collection
Added Xiaoya_Luo.jpg to collection mayoe23-face-collection
Added Xiaoya_Luo_aged.jpg to collection mayoe23-face-collection
Added Xiaoyang_Zheng.jpg to collection mayoe23-face-collection
Added Xiaoyang_Zheng_aged.jpg to collection mayoe23-face-collection
Added Xiaoyu_Zong.jpg to collection mayoe23-face-collection
Added Xiaoyu_Zong_aged.jpg to collection mayoe23-face-collection
Added Xingyu_Wan.jpg to collection mayoe23-face-collection
Added Xingyu_Wan_aged.jpg to collection mayoe23-face-collection
Added Xiyan_Huang.jpg to collection mayoe23-face-collection
Added Xiyan_Huang_aged.jpg to collection mayoe23-face-collection
Added Xiyue_Yu.jpg to collection mayoe23-face-collection
Added Xiyue_Yu_aged.jpg to collection mayoe23-face-collection
Added Yanghua_Zhang.jpg to collection mayoe23-face-collection
Added Yanghua_Zhang_aged.jpg to collection mayoe23-face-collection
Added Yilin_Wang.jpg to collection mayoe23-face-collection
Added Yilin_Wang_aged.jpg to collection mayoe23-face-collection
Added Yiming_Xu.jpg to collection mayoe23-face-collection
Added Yiming_Xu_aged.jpg to collection mayoe23-face-collection
Added Yuchen_Qin.jpg to collection mayoe23-face-collection
Added Yuchen_Qin_aged.jpg to collection mayoe23-face-collection
Added Yue_Zhou.jpg to collection mayoe23-face-collection
Added Yue_Zhou_aged.jpg to collection mayoe23-face-collection
Added Yutong_Ouyang.jpg to collection mayoe23-face-collection
Added Yutong_Ouyang_aged.jpg to collection mayoe23-face-collection
Added Zaul_Alexander_Perez.jpg to collection mayoe23-face-collection
Added Zaul_Alexander_Perez_aged.jpg to collection mayoe23-face-collection
Added Zihe_Liu.jpg to collection mayoe23-face-collection
Added Zihe_Liu_aged.jpg to collection mayoe23-face-collection

Searching for Faces by Images¶

In [8]:
client=boto3.client('rekognition')

response=client.search_faces_by_image(CollectionId=collection_id,
                            Image={'S3Object':{'Bucket':bucket_name,'Name':'Eric_Mayo.jpg'}},
                            FaceMatchThreshold=90,
                            MaxFaces=1)


faceMatches=response['FaceMatches']
print ('Matching faces')
for match in faceMatches:
        print ('FaceId:' + match['Face']['FaceId'])
        print ('Similarity: ' + "{:.2f}".format(match['Similarity']) + "%")
        print
Matching faces
FaceId:964d458b-a323-42ca-886f-9fb8f3eece0d
Similarity: 100.00%

Running Similarities to Find Matches¶

In [9]:
match_file = pd.read_excel(r"C:\Users\ericm\OneDrive\Desktop\Data Management\FinalMatchSourceTarget.xlsx")
# Replace '.jpeg' with '.jpg'
match_file['source_image'] = match_file['source_image'].str.replace('.jpeg', '.jpg')
match_file['target_image'] = match_file['target_image'].str.replace('.jpeg', '.jpg')

match_file.head()
C:\Users\ericm\AppData\Local\Temp\ipykernel_37592\3172586465.py:3: FutureWarning: The default value of regex will change from True to False in a future version.
  match_file['source_image'] = match_file['source_image'].str.replace('.jpeg', '.jpg')
C:\Users\ericm\AppData\Local\Temp\ipykernel_37592\3172586465.py:4: FutureWarning: The default value of regex will change from True to False in a future version.
  match_file['target_image'] = match_file['target_image'].str.replace('.jpeg', '.jpg')
Out[9]:
match_id source_image name target_image expected_match
0 100 Bingyu_Li.jpg Bingyu_Li Bingyu_Li_aged.jpg match
1 101 Whitney_Joyce_Isbell.jpg Whitney_Joyce_Isbell Whitney_Joyce_Isbell_aged.jpg match
2 102 Qian_Chen.jpg Qian_Chen Qian_Chen_aged.jpg match
3 103 Hanshuai_Shi.jpg Hanshuai_Shi Hanshuai_Shi_aged.jpg match
4 104 Ruochen_Bao.jpg Ruochen_Bao Ruochen_Bao_aged.jpg match
In [10]:
def compare_faces(bucket, sourceFile, targetFile):
    client = boto3.client('rekognition')
    similarity = 0  # Default value in case no face match is found

    try:
        response = client.compare_faces(SimilarityThreshold=80,
                                        SourceImage={'S3Object': {'Bucket': bucket, 'Name': sourceFile}},
                                        TargetImage={'S3Object': {'Bucket': bucket, 'Name': targetFile}})

        # Check if any face matches are found
        if response['FaceMatches']:
            faceMatch = response['FaceMatches'][0]  # Get the first match
            similarity = faceMatch["Similarity"]
    
    except Exception as e:
        print(f"An error occurred: {e}")

    return similarity
In [11]:
# Specify the S3 bucket name
bucket_name = 'mayoe23-final-bucket'
match_file['match_similarity'] = match_file.apply(lambda row: compare_faces(bucket_name, row['source_image'], row['target_image']), axis=1)
An error occurred: An error occurred (InvalidParameterException) when calling the CompareFaces operation: Request has invalid parameters
An error occurred: An error occurred (InvalidS3ObjectException) when calling the CompareFaces operation: Unable to get object metadata from S3. Check object key, region and/or access permissions.
An error occurred: An error occurred (InvalidS3ObjectException) when calling the CompareFaces operation: Unable to get object metadata from S3. Check object key, region and/or access permissions.
An error occurred: An error occurred (InvalidS3ObjectException) when calling the CompareFaces operation: Unable to get object metadata from S3. Check object key, region and/or access permissions.

Looking at Matches & Non-Matches¶

In [12]:
import numpy as np 
match_file['predicted_match'] = np.where(match_file['match_similarity'] > 50, 'match','no-match')
match_file.head()
Out[12]:
match_id source_image name target_image expected_match match_similarity predicted_match
0 100 Bingyu_Li.jpg Bingyu_Li Bingyu_Li_aged.jpg match 98.274345 match
1 101 Whitney_Joyce_Isbell.jpg Whitney_Joyce_Isbell Whitney_Joyce_Isbell_aged.jpg match 97.822098 match
2 102 Qian_Chen.jpg Qian_Chen Qian_Chen_aged.jpg match 0.000000 no-match
3 103 Hanshuai_Shi.jpg Hanshuai_Shi Hanshuai_Shi_aged.jpg match 89.793312 match
4 104 Ruochen_Bao.jpg Ruochen_Bao Ruochen_Bao_aged.jpg match 0.000000 no-match
In [13]:
match_file[match_file['source_image'] == 'Eric_Mayo.jpg']
Out[13]:
match_id source_image name target_image expected_match match_similarity predicted_match
56 156 Eric_Mayo.jpg Eric_Mayo Eric_Mayo_aged.jpg match 93.131035 match
169 269 Eric_Mayo.jpg NaN John_William_Null_aged.jpg no match 0.000000 no-match

Confusion Matrix & Scores¶

In [14]:
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score

# Calculate confusion matrix
matrix = confusion_matrix(match_file['expected_match'], 
                          match_file['predicted_match'], 
                          labels=["match", "no-match"])

print(matrix)
[[89 37]
 [ 0  0]]
In [15]:
match_file['expected_match'] = match_file['expected_match'].str.replace('no match', 'no-match')

# Calculate confusion matrix
y_true = match_file['expected_match']
y_pred = match_file['predicted_match']
labels = ["match", "no-match"]
matrix = confusion_matrix(y_true, y_pred, labels=labels)

# Calculate Accuracy, Precision and Recall
accuracy = accuracy_score(y_true, y_pred)
precision = precision_score(y_true, y_pred, pos_label="match")
recall = recall_score(y_true, y_pred, pos_label="match")

print("Accuracy:", accuracy)
print("Precision:", precision)
print("Recall:", recall)
Accuracy: 0.7897727272727273
Precision: 1.0
Recall: 0.7063492063492064
In [16]:
# Plotting using seaborn
plt.figure(figsize=(8, 6))
sns.heatmap(matrix, annot=True, fmt="d", xticklabels=labels, yticklabels=labels, cmap="Blues")
plt.title("Confusion Matrix")
plt.ylabel('Actual')
plt.xlabel('Predicted')
plt.show()